package com.ysc.plugin.utility

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.ysc.plugin.common.LocalBroadcastAction
import com.ysc.plugin.common.PictureType
import com.ysc.plugin.common.abstract.Manager
import com.ysc.plugin.common.abstract.Plugin
import com.ysc.plugin.utility.network.NetWorkManager
import com.ysc.plugin.utility.photo.PhotoManger
import com.ysc.plugin.utility.photo.clip.ClipPhoto
import com.ysc.plugin.utility.receiver.UtilityReceiver
import org.json.JSONObject
import java.io.File
import java.lang.reflect.Method

class Utility() :Plugin() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        private var instance: Utility?= null
        fun getInstance(): Utility? {
            instance ?: synchronized(this) {
                instance ?: Utility().apply { instance = this }
            }
            return instance
        }
    }

    override fun initialize(activity:Activity){
        super.setActivity(activity)
        initManager()
    }

    init {
        instance = this
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        TODO("Not yet implemented")
    }

    override fun onDestroy() {
        //LocalBroadcastManager.getInstance(super.getActivity()!!).unregisterReceiver(UtilityReceiver())
    }

    override fun getHelp(): String {
       return ""
    }

    override fun getName(): String {
        return "Utility"
    }

    override fun getVersion(): String {
        return "1.0.0"
    }

    override fun initManager() {
        addPluginManager(PhotoManger())
        addPluginManager(NetWorkManager())
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        for (pluginModule in getPluginManager()){
                pluginModule.value.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

    fun installApk(file: File){
        val it = Intent()
        it.action = Intent.ACTION_VIEW
        val fileUri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(super.getActivity()!!, super.getActivity()!!.packageName + ".fileprovider", file)
        } else {
            Uri.fromFile(file)
        }
        it.flags = Intent.FLAG_ACTIVITY_NEW_TASK // 防止打不开应用
        it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        it.setDataAndType(fileUri, "application/vnd.android.package-archive")
        super.getActivity()!!.startActivity(it)
    }

}